package com.mask.im.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mask.im.business.common.util.MaskIMSecurityUtils;
import com.mask.im.business.mapper.IMChatListMapper;
import com.mask.im.business.mapper.IMFriendRelationMapper;
import com.mask.im.business.mapper.IMGroupChatMapper;
import com.mask.im.business.model.entity.chat.*;
import com.mask.im.business.model.vo.IMChatListVO;
import com.mask.im.business.model.vo.IMFriendVO;
import com.mask.im.business.model.vo.IMGroupChatVO;
import com.mask.im.business.common.model.RestResponse;
import com.mask.im.business.service.ChannelService;
import com.mask.im.business.service.IMChatListService;
import com.mask.token.util.MaskSecurityUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 创建聊天列表数据
 *
 * @author jian
 */
@Log4j2
@Service
public class IMChatListServiceImpl extends ServiceImpl<IMChatListMapper, IMChatListDO> implements IMChatListService {

    @Resource
    private IMFriendRelationMapper friendRelationMapper;

    @Resource
    private IMGroupChatMapper groupChatMapper;

    @Resource
    private ChannelService channelService;

    @Override
    public void creatChatData(Long targetId, Integer type) {
        Long userId = MaskSecurityUtil.getCurrentUserId();
        if (null != userId) {
            //校验是否存在聊天数据
            IMChatListDO imChatList = this.baseMapper.selectOne(new LambdaQueryWrapper<IMChatListDO>().eq(IMChatListDO::getUserId, userId).eq(IMChatListDO::getTargetId, targetId));
            if (null == imChatList) {
                //不存在则创建新的群聊信息
                imChatList = new IMChatListDO();
                if (1 == type) {
                    //获取对应的用户或者是群组消息
                    IMFriendVO friendData = friendRelationMapper.getFriendData(userId, targetId);
                    imChatList.setOriginalName(friendData.getFriendNickname());
                    imChatList.setCustomRemark(friendData.getRemarkName());
                    imChatList.setChatAvatar(friendData.getFriendAvatar());
                } else {
                    IMGroupChatVO groupData = groupChatMapper.getGroupData(userId, targetId);
                    imChatList.setOriginalName(groupData.getGroupName());
                    imChatList.setCustomRemark(groupData.getRemarkName());
                    imChatList.setChatAvatar(groupData.getGroupAvatar());
                }
                imChatList.setUnreadCount(0);
                imChatList.setIsTop(0);
                imChatList.setIsMuted(0);
                imChatList.setIsDeleted(0);
                imChatList.setCreateTime(new Date());
                imChatList.setUserId(userId.longValue());
                imChatList.setChatType(type);
                imChatList.setTargetId(targetId.longValue());
                baseMapper.insert(imChatList);
            } else if (imChatList.getIsDeleted() == 0) {
                //存在删除则推送到前台列表,并将删除状态修改为未删除
                imChatList.setIsDeleted(0);
                baseMapper.updateById(imChatList);
            }
        }
    }

    @Override
    public RestResponse<List<IMChatListVO>> getChatList(String keyword) {
        Long userId = MaskSecurityUtil.getCurrentUserId();
        //获取所有在线成员
        Set<String> userIds = ChannelServiceImpl.userIdChannel.keySet();

        List<IMChatListDO> imChatLists = baseMapper.selectList(new LambdaQueryWrapper<IMChatListDO>().eq(IMChatListDO::getUserId, userId).eq(IMChatListDO::getIsDeleted, 0));
        List<IMChatListVO> imChatList = BeanUtil.copyToList(imChatLists, IMChatListVO.class);
        List<IMChatListVO> collect = imChatList.stream().sorted(Comparator.comparingInt(IMChatListVO::getUnreadCount).reversed().thenComparing(IMChatListVO::getLatestTime, Comparator.reverseOrder())).peek(item -> {
            if (userIds.contains(item.getTargetId())) {
                item.setIsOnline(0);
            } else {
                item.setIsOnline(1);
            }
        }).collect(Collectors.toList());
        return RestResponse.ok(collect);
    }


    @Override
    public void createSingleChatSession(Long userIdA, Long userIdB) {
        IMChatListDO chatListDOA = new IMChatListDO();
        chatListDOA.setUserId(userIdA);
        chatListDOA.setTargetId(userIdB);
        //单聊
        chatListDOA.setChatType(1);
        baseMapper.insert(chatListDOA);

        // 创建 B→A 的关系（双向）
        IMChatListDO chatListDOB = new IMChatListDO();
        chatListDOB.setUserId(userIdB);
        chatListDOB.setTargetId(userIdA);
        //单聊
        chatListDOB.setChatType(1);
        baseMapper.insert(chatListDOB);
    }

    @Override
    public void updateChatLastMessage(IMFriendChatMessageDO chatMessageDO) {
        Long userId = MaskSecurityUtil.getCurrentUserId();
        List<IMChatListDO> chatListDOList = this.baseMapper.selectList(new LambdaQueryWrapper<IMChatListDO>()
                .eq(IMChatListDO::getUserId, chatMessageDO.getSenderId()).eq(IMChatListDO::getTargetId, chatMessageDO.getReceiverId())
                .or()
                .eq(IMChatListDO::getUserId, chatMessageDO.getReceiverId()).eq(IMChatListDO::getTargetId, chatMessageDO.getSenderId()));
        chatListDOList.forEach(item -> {
            item.setLatestTime(chatMessageDO.getCreateTime());
            item.setMessageType(chatMessageDO.getMessageType());
            item.setLatestMessage(chatMessageDO.getContent());
            item.setLatestMessageId(chatMessageDO.getId());
            item.setUnreadCount(!item.getUserId().equals(userId) ? item.getUnreadCount() + 1 : item.getUnreadCount());
            log.info("需要更新的值：{}", item);
            this.baseMapper.updateById(item);
        });
    }

    @Override
    public void createGroupChatList(IMGroupChatDO imGroupChat, List<Long> userInfoIds) {
        //循环用户数据批量创建群组聊天数据
        for (Long userInfoId : userInfoIds) {
            IMChatListDO chatListDO = new IMChatListDO();
            chatListDO.setChatAvatar(imGroupChat.getGroupAvatar());
            chatListDO.setDisplayName(imGroupChat.getGroupName());
            chatListDO.setCustomRemark(imGroupChat.getGroupName());
            chatListDO.setChatType(2);
            chatListDO.setTargetId(imGroupChat.getId());
            chatListDO.setUnreadCount(0);
            chatListDO.setIsDeleted(0);
            chatListDO.setCreateTime(new Date());
            chatListDO.setUserId(userInfoId);
            chatListDO.setIsMuted(0);
            chatListDO.setIsTop(0);
            chatListDO.setLatestTime(new Date());
            baseMapper.insert(chatListDO);
        }
    }

    @Override
    public void clearUnreadCount(Long friendId) {
        Long userId = MaskSecurityUtil.getCurrentUserId();
        this.baseMapper.update(null, new LambdaUpdateWrapper<IMChatListDO>()
                .set(IMChatListDO::getUnreadCount, 0)
                .eq(IMChatListDO::getUserId, userId)
                .eq(IMChatListDO::getTargetId, friendId));
    }
}
